import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardHeader, CardContent } from '@/components/ui/card'

export default function ForgotPassword() {
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [verifyCode, setVerifyCode] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [step, setStep] = useState(1)
  const [error, setError] = useState('')
  const [countdown, setCountdown] = useState(0)

  const handleRequestReset = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      })
      if (!response.ok) {
        throw new Error('重置密码请求失败')
      }
      setStep(2)
      setCountdown(60)
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    } catch (error) {
      setError('发送重置邮件失败，请重试')
    }
  }

  const handleConfirmReset = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const response = await fetch('/api/auth/reset-password/confirm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code: verifyCode, newPassword }),
      })
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.error || '重置密码失败')
      }
      navigate('/login', { replace: true })
    } catch (error: any) {
      setError(error.message)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
    <Card className="w-[400px]">
      <CardHeader>
        <h2 className="text-2xl font-bold text-center">找回密码</h2>
      </CardHeader>
      <CardContent>
        {error && (
          <div className="text-red-500 text-sm text-center mb-4">{error}</div>
        )}
        {step === 1 ? (
          <form onSubmit={handleRequestReset} className="space-y-4">
            <Input
              type="email"
              placeholder="邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <Button type="submit" className="w-full">
              发送验证码
            </Button>
          </form>
        ) : (
          <form onSubmit={handleConfirmReset} className="space-y-4">
            <div className="flex gap-2">
              <Input
                type="text"
                placeholder="验证码"
                value={verifyCode}
                onChange={(e) => setVerifyCode(e.target.value)}
                required
              />
              <Button
                type="button"
                variant="outline"
                onClick={handleRequestReset}
                disabled={countdown > 0}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '重新发送'}
              </Button>
            </div>
            <Input
              type="password"
              placeholder="新密码"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              required
              minLength={6}
            />
            <Button type="submit" className="w-full">
              重置密码
            </Button>
          </form>
        )}
        <div className="text-center mt-4">
          <Link to="/login" className="text-blue-600 hover:text-blue-800">
            返回登录
          </Link>
        </div>
      </CardContent>
    </Card>
  </div>
  )
}